import CustomTextArea from '@/components/antd-comp/input/CustomTextArea'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { initNodeData } from '@/pages/workflow/constants'
import { useDictStore } from '@/store/dictStore'
import { useWorkFlowStore } from '@/store/workflowStore'
import { useBuriedEvent } from '@/util/buried'
import { LoadingOutlined } from '@ant-design/icons'
import { Button, Input, Modal, Select } from 'antd'
import { cloneDeep } from 'lodash'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import IconUpload from '../../components/antd-comp/icon-upload'
import { workflowCreateApi, workflowEditApi } from './API'
import './style/flowCreate.css'

const FlowCreate = ({ open, setOpen, dropList, obj, submitData }) => {
  // ------埋点------
  const { skillsBuriedEvent } = useBuriedEvent()
  const { initFlow } = useWorkFlowStore()

  /* 取消 */
  const handleCancel = () => {
    skillsBuriedEvent({
      page: obj?.id ? '编辑工作流弹窗' : '创建工作流弹窗',
      event_name: '【取消】按钮',
      data_id: obj.id
    })
    setOpen(false)
    setFormData({ name: '', desc: '', logo: '', category_code: '', id: '' })
  }
  const { t } = useTranslation()
  // State for form fields
  const [formData, setFormData] = useState({
    name: '',
    desc: '',
    logo: '',
    category_code: '',
    id: ''
  })

  useEffect(() => {
    setFormData({
      ...formData,
      ...obj
    })
    if (obj.id) {
      setFormData({
        ...formData,
        ...obj,
        category_code: obj.category_code ? Number(obj.category_code) : null
      })
    }
  }, [])
  const [loading, setLoading] = useState(false)
  // State for errors
  const [errors, setErrors] = useState<any>({})

  // Validate form fields
  const validateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return t('build.nameRequired')
        if (value.length > 30) return '名称最多30个字符'
        return ''
      case 'category_code':
        //if (!value) return t('build.category_codeRequired')
        return ''
      case 'desc':
        if (!value) return '描述不能为空'
        if (value.length < 20) return t('application.promptForBetter')
        if (value.length > 500) return '描述不能大于200个字符'
        return ''
      default:
        return ''
    }
  }
  const generateAiValidateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return t('build.nameRequired')
        if (value.length > 8) return '名称最多8个字符'
        return ''
      case 'desc':
        if (!value) return 'AI生成icon时描述不能为空'
        return ''
      default:
        return ''
    }
  }

  const generateAiValidateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(formData).forEach(key => {
      const error = generateAiValidateField(key, formData[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }

  // Handle field change
  const handleChange = (e, type) => {
    const error = validateField(type, e)
    setErrors(prev => ({ ...prev, [type]: error }))
    if (type === 'name') {
      setFormData(prev => ({ ...prev, name: e }))
    } else if (type === 'category_code') {
      setFormData(prev => ({ ...prev, category_code: e }))
    } else if (type === 'desc') {
      setFormData(prev => ({ ...prev, desc: e }))
    }
  }

  // Validate entire form
  const validateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(formData).forEach(key => {
      const error = validateField(key, formData[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }
  const { loadDictOptions } = useDictStore()
  // 异步函数来获取默认Logo
  const defLogoFun = async () => {
    try {
      const res = await loadDictOptions('icon')
      if (res && res.length) {
        return res[Math.floor(Math.random() * res.length)].value
      }
    } catch (error) {
      console.error('Error loading dict options:', error)
    }
  }
  /* 提交 */
  const handleSubmit = async e => {
    e.preventDefault()
    const isValid = validateForm()
    if (isValid) {
      setLoading(true)
      /* 没有选择就获取默认logo */
      let logo = formData.logo
      if (!formData.logo) {
        logo = await defLogoFun()
      }
      const data = {
        name: formData.name,
        description: formData.desc,
        logo,
        category_code: formData.category_code? formData.category_code : 0
      }
      
      if (formData?.id) {
        workflowEditApi(formData.id, data)
          .then((res: any) => {
            if (res) {
              skillsBuriedEvent({
                page: '编辑工作流弹窗',
                event_name: '【确定】按钮',
                data_id: res.id,
                detail: JSON.stringify({ 类型: formData.category_code, 结果: '成功' })
              })
              handleCancel()
              submitData(res)
              initFlow(res)
            }
          })
          .catch(() => {
            skillsBuriedEvent({
              page: '编辑工作流弹窗',
              event_name: '【确定】按钮',
              detail: JSON.stringify({ 类型: formData.category_code, 结果: '失败' })
            })
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        const createSubmitData: any = cloneDeep(data)
        createSubmitData.graph = initNodeData()
        workflowCreateApi(createSubmitData)
          .then((res: any) => {
            if (res) {
              skillsBuriedEvent({
                page: '创建工作流弹窗',
                event_name: '【确定】按钮',
                data_id: res.id,
                detail: JSON.stringify({ 类型: formData.category_code, 结果: '成功' })
              })
              handleCancel()
              submitData(res)
            }
          })
          .catch(() => {
            skillsBuriedEvent({
              page: '创建工作流弹窗',
              event_name: '【确定】按钮',
              detail: JSON.stringify({ 类型: formData.category_code, 结果: '失败' })
            })
          })
          .finally(() => {
            setLoading(false)
          })
      }
    }
  }
  /**
   * ICON上传组件相关
   */
  const [iconFileList] = useState([])
  const handleSelectPic = pic => {
    setFormData(prev => ({ ...prev, logo: pic }))
  }

  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case"
        title={formData?.id ? '编辑工作流' : '创建工作流'}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button key="cancel" className="closeBtnStyles closeBtnWid" shape="round" onClick={handleCancel}>
            {t('cancel')}
          </Button>,
          <ThemeBtn key="create" disabled={loading} className="closeBtnWid" onClick={handleSubmit}>
            {loading && <LoadingOutlined className="mr-2" />}
            确定
          </ThemeBtn>
        ]}
      >
        <div
          style={{ overflowY: 'scroll', height: '616px' }}
          className="flex flex-col gap-4 py-2 pr-1 sm:max-w-[825px]"
        >
          {/* name */}
          <div className="">
            <label htmlFor="name" className="bisheng-label">
              工作流名称
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              id="name"
              name="name"
              autoComplete="off"
              placeholder="给工作流取个名字"
              className="inputHig contMarginTop"
              value={formData.name}
              onChange={e => handleChange(e.target.value, 'name')}
            />
            {errors.name && <p className="bisheng-tip mt-1">{errors.name}</p>}
          </div>
          {/* type */}
          {/* <div className="caseMarginTop">
            <label htmlFor="category_code" className="bisheng-label">
              工作流类型
              <span className="bisheng-tip">*</span>
            </label>
            <div className="contMarginTop">
              <Select
                key={'createApplication_select'}
                className="inoutHig"
                placeholder={'工作流类型'}
                value={formData.category_code ? formData.category_code : null}
                style={{ width: '100%' }}
                onChange={val => handleChange(val, 'category_code')}
                options={dropList}
                fieldNames={{ label: 'label', value: 'id' }}
              />
            </div>
            {errors.category_code && <p className="bisheng-tip mt-1">{errors.category_code}</p>}
          </div> */}
          {/* desc */}
          <div className="caseMarginTop">
            <label htmlFor="desc" className="bisheng-label">
              {t('application.appliPageDiadesc')}
              <span className="bisheng-tip">*</span>
            </label>
            <CustomTextArea
              id="desc"
              name="desc"
              placeholder={'请描述这个工作流的功能和用途，以便大模型更好地理解并进行调用'}
              maxLength={200}
              className="contMarginTop min-h-32"
              value={formData.desc}
              onChange={e => {
                handleChange(e.target.value, 'desc')
              }}
            />
            {errors.desc && <p className="bisheng-tip mt-1">{errors.desc}</p>}
          </div>
          {/* icon */}
          <div className="caseMarginTop">
            <IconUpload
              defaultFileList={iconFileList}
              logo={formData.logo}
              name={formData.name}
              description={formData.desc}
              validateMethod={generateAiValidateForm}
              onSelect={pic => handleSelectPic(pic)}
            ></IconUpload>
          </div>
        </div>
      </Modal>
    </>
  )
}

export default FlowCreate
